package main

// 如何优雅地重试 https://www.infoq.cn/article/5fboevkal0gvgvgeac4z
// ref: https://gocn.vip/topics/17395
import (
	"crypto/tls"
	"fgo/advance/http/http/retry/retry"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/httptest"
	"time"
)
type RetryAfterError struct {
	response http.Response
}

func (err RetryAfterError) Error() string {
	return fmt.Sprintf(
		"Request to %s fail %s (%d)",
		err.response.Request.RequestURI,
		err.response.Status,
		err.response.StatusCode,
	)
}
type SomeOtherError struct {
	err        string
	retryAfter time.Duration
}

func (err SomeOtherError) Error() string {
	return err.err
}

// use https://github.com/aereal/go-httpretryafter instead
func parseRetryAfter(_ string) (time.Time, error) {
	return time.Now().Add(1 * time.Second), nil
}

func main() {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "hello")
	}))
	defer ts.Close()

	var body []byte

	err := retry.Do(
		func() error {
			// 1. 给请求设置超时时间
			tr := &http.Transport{
				Dial: (&net.Dialer{
					Timeout: 3 * time.Second,
				}).Dial,
				MaxIdleConns:    4,
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}
			// Create client
			client := &http.Client{Transport: tr, Timeout: time.Second * 5}
			req, err := http.NewRequest("GET", "https://www.google.com.hk/?gws_rd=cr,ssl", nil)
			if err != nil {
				return err
			}
			resp, err := client.Do(req)

			// resp, err := http.Get("https://www.google.com.hk/?gws_rd=cr,ssl")
			// 2. 利用 go httptest.NewServer 测试
			//resp, err := http.Get(ts.URL)
			if err == nil {
				defer func() {
					if err := resp.Body.Close(); err != nil {
						panic(err)
					}
				}()
				body, err = ioutil.ReadAll(resp.Body)
			}

			return err
		},

		retry.DelayType(func(n uint, err error, config *retry.Config) time.Duration {
			switch e := err.(type) {
			case RetryAfterError:
				if t, err := parseRetryAfter(e.response.Header.Get("Retry-After")); err == nil {
					return time.Until(t)
				}
			case SomeOtherError:
				return e.retryAfter
			}

			//default is backoffdelay
			return retry.BackOffDelay(n, err, config)
		}),
		retry.Attempts(2),
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))
}
